package com.just.springbootbatch.batch;

import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 校验
 * @param <T>
 */
public class CsvBeanValidator<T> implements Validator<T>,InitializingBean {
    private javax.validation.Validator validator;

    /**
     * 使用validator的validate方法校验数据
     */
    @Override
    public void validate(T t) throws ValidationException {
        Set<ConstraintViolation<T>> constraintViolations=validator.validate(t);
        if(constraintViolations.size()>0){
            StringBuilder sb=new StringBuilder();
            for(ConstraintViolation<T> constraintViolation:constraintViolations){
                sb.append(constraintViolation.getMessage()).append("\n");
            }
            throw new ValidationException(sb.toString());
        }
    }

    /**
     * 使用jsr-303的validator来校验我们的数据
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        ValidatorFactory validatorFactory=Validation.buildDefaultValidatorFactory();
        validator=validatorFactory.usingContext().getValidator();
    }
}
